/*
* Licensed under the MIT License
* 
* Copyright (c) 2010 Kay Kreuning
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* 
* http://code.google.com/p/as3hyvesapi
*/
package nl.hyves.api.authorization
{
	import flash.events.Event;
	import flash.net.SharedObject;
	import flash.utils.getTimer;
	import flash.utils.setTimeout;
	
	import nl.hyvesstudio.oauth.Accesstoken;
	import nl.hyvesstudio.oauth.IOAuthService;
	import nl.hyvesstudio.oauth.authorization.IAuthorizer;
	
	/**
	 * This class uses an already saved accesstoken for authorization,
	 * if there is no accesstoken available the backup authorizer will be used to retrieve one.
	 * 
	 * @author Kay Kreuning
	 */
	public class LocalTokenAuthorizer implements IAuthorizer
	{
		private static const SO_ID:String = "nl.hyves.api.authorization.LocalTokenAuthorizer.SO_ID";
		
		/**
		 * Clear (if available) the current stored token.
		 */
		public static function clear():void
		{
			SharedObject.getLocal(SO_ID).clear();
		}
		
		private var backupAuthorizer:IAuthorizer
		private var so:SharedObject;
		private var oauthService:IOAuthService;
		
		/**
		 * Construct a new LocalTokenAuthorizer instance.
		 * 
		 * @param backupAuthorizer <code>IAuthorizer</code> instance used to retrieve the accesstoken if none is available
		 */
		public function LocalTokenAuthorizer(backupAuthorizer:IAuthorizer)
		{
			this.backupAuthorizer = backupAuthorizer;
			so = SharedObject.getLocal(SO_ID);
		}
		
		/** @inheritDoc */
		public function authorize(oauthService:IOAuthService):void
		{
			this.oauthService = oauthService;
			
			if (so.data.userId != null && so.data.methods != null)
			{
				if (new Date().getTime() >= so.data.expireDate.getTime())
				{
					// Token is expired, get a new one.
					
					clear();
					authorize(oauthService);
					
					return;
				}
				
				// Delay one frame so that event listeners on the OAuthService can catch up
				setTimeout(updateServiceWithToken, 1, new Accesstoken(
					so.data.token,
					so.data.tokenSecret,
					so.data.userId,
					so.data.methods,
					so.data.expireDate));
			}
			else
			{
				oauthService.addEventListener(Event.COMPLETE, onAuthorizer, false, 0, true);
				
				backupAuthorizer.authorize(oauthService);
			}
		}
		
		private function updateServiceWithToken(accesstoken:Accesstoken):void
		{
			oauthService.accesstoken = accesstoken;
		}
		
		private function onAuthorizer(event:Event):void
		{
			var token:Accesstoken = oauthService.accesstoken;
			
			so.data.token = token.token;
			so.data.tokenSecret = token.secret;
			so.data.userId = token.userId;
			so.data.methods = token.methods;
			so.data.expireDate = token.expireDate;
			
			so.flush();
		}
	}
}